<template>
  <div>
    <h1>因子数据配置</h1>
    <div>
      <a-row>
        <a-col :span="24">
          <a-button @click="addFeature"><a-icon type="file-add" />添加决策因子</a-button>
          <!-- <a-button class="editable-add-btn" @click="viewModel">查看</a-button> -->
          <!-- <a-button @click="getDynamicModel"><a-icon type="build" />模型</a-button> -->
          <a-button @click="downloadTemplate"><a-icon type="download" />模板</a-button>
          <a-button @click="saveModelData"><a-icon type="save" />保存</a-button>
          <a-button @click="loadModelData"><a-icon type="search" />加载</a-button>
          <a-upload name="file" :multiple="false" :action="uploadUrl" @change="handleChange">
            <a-button> <a-icon type="upload" />导入</a-button>
          </a-upload>
          <hr>
        </a-col>
      </a-row>
      <a-row>
        <dmt-value @onValueUpdate="onValueUpdate"></dmt-value>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item label="决策表名称">
            <a-input v-model="dmtName"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="决策表代码">
            <a-input v-model="mem"/>
          </a-form-item>
        </a-col>
      </a-row>
      <hr/>
      <a-row>
        <a-col :span="24">
          <feature-combine :rowFeatures="selectedItems" @onFeatureUpdate="onFeatureUpdate"/>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="hhead"
      :data-source="hdata"
      :customHeaderRow="customHeaderRow"
      :pagination="false"
      bordered
      :scroll="{ x: 'calc(700px + 50%)', y: 400 }">
      <template slot="name" slot-scope="text, record, scope, columnDef">
        <editable-cell :text="text" @change="onCellChange(record.key, scope, $event, text, columnDef)" />
      </template>
    </a-table>

    <a-modal v-model="addFeatureVisible" title="添加因子" :closable="true" @ok="handleOk">
      <a-button @click="getAllFeatures">查询</a-button>
      <a-table
      :columns="featureColumn"
      :data-source="featureData"
      :pagination="false"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      ></a-table>
    </a-modal>
  </div>
</template>
<script>
import EditableCell from './EditableCell'
import FeatureItem from './FeatureItem'
import FeatureCombine from './FeatureCombine'
import DmtValue from './DmtValue'
import { getDmtModel, downloadTemplate, saveDmtModel, loadDmtModel, getFeatures } from '@/api/dmt'

const installColumnRender = (columDef) => {
  if (columDef.children != null && columDef.children.length > 0) {
    columDef.children.forEach(v => {
      installColumnRender(v)
    })
  } else {
    columDef.scopedSlots = { customRender: 'name' }
  }
}

const featureColumn = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '因子代码',
    dataIndex: 'featureCode',
    key: 'featureCode'
  },
  {
    title: '因子名称',
    dataIndex: 'featureName',
    key: 'featureName'
  }
]

/**
 * 这里的2是当前这一列的分区大小
 * @param {*} value
 * @param {*} row
 * @param {*} index
 * @returns
 */
export default {
  components: {
    EditableCell,
    FeatureItem,
    FeatureCombine,
    DmtValue
  },
  computed: {
    uploadUrl: function () {
      const upload = 'http://localhost:4000/api/dmt/model/upload/' + this.model.code
      return upload
    }
  },
  data () {
    return {
      dmtName: 'aaa',
      mem: 'ss',
      hhead: [],
      hdata: [],
      rowClassName: 'rowClassName',
      model: {},

      selectedKeys: [],
      filteredItems: [],
      disabled: false,

      addFeatureVisible: false,
      featureColumn: featureColumn,
      featureData: [],

      selectedRowKeys: [],
      selectedFeatures: [],

      selectedItems: [],

      param: {},

      dmtValues: []
    }
  },
  methods: {
    onValueUpdate: function (values) {
      console.log('返回值模型数据:', values)
      this.dmtValues = values
    },
    onFeatureUpdate: function (param) {
      param.name = this.dmtName
      console.log('因子组合发生变化:', param)

      this.param = param

      this.hdata = []
      this.hhead = []

      getDmtModel(param).then(response => {
        const data = response.model
        const meta = response.meta
        const head = response.head

        this.model = response

        this.hdata = data
        this.hdata.forEach(record => {
          record.meta = meta
        })

        head.forEach(h => {
          if (h.cardinal) {
            h.customRender = this.columnHeadRender
          } else {
            installColumnRender(h)
          }
        })

        this.hhead = head
      })
    },
    getAllFeatures: function () {
      getFeatures().then(response => {
        this.featureData = response
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys

      this.selectedFeatures = []
      this.selectedRowKeys.forEach(v => {
        this.selectedFeatures.push(this.featureData[v])
      })
    },
    addFeature: function () {
      this.addFeatureVisible = true
    },
    handleOk: function (e) {
      this.addFeatureVisible = false

      this.selectedItems = this.selectedFeatures.map(v => {
          return {
            key: v.featureCode,
            title: v.featureName
          }
      })

      console.log('选中的因子:', this.selectedFeatures)
    },
    handleDisable (disabled) {
      this.disabled = disabled
    },
    customHeaderRow: function (record) {
      return {
        class: 'mclass',
        on: {
          click: (row) => {}
        }
      }
    },
    /**
     * 决策表上编辑的值更新到模型上.
     */
    onCellChange: function (index, rowIndex, newValue, oldValue, columnDef) {
      const column = columnDef.dataIndex
      this.hdata[rowIndex][column] = newValue
    },
    /**
     * 自定义的列表头渲染器
     */
    columnHeadRender: (value, row, index, p) => {
      const obj = {
        children: value,
        attrs: {},
        style: {}
      }

      // 合并表头行数据
      if (!p.cardinal) {
        p.cardinal = 1
      }

      if (index % p.cardinal === 0) {
        obj.attrs.rowSpan = p.cardinal
      } else {
        obj.attrs.rowSpan = 0
      }

      const even = (element) => element === p.key
      const has = row.meta.colFields.some(even)
      if (has) {
        obj.style = {
          'color': '#A00',
          'background-color': '#FAFAFA'
        }
      }

      return obj
    },

    handleChange: function () {
      console.log('handle change happend.')
    },

    loadModelData: function () {
      this.hdata = []
      this.hhead = []

      const code = this.model.code
      if (!code) {
        return
      }

      loadDmtModel(code).then(response => {
        const data = response.model
        const meta = response.meta
        const head = response.head

        this.model = response

        this.hdata = data
        this.hdata.forEach(record => {
          record.meta = meta
        })

        head.forEach(h => {
          if (h.cardinal) {
            h.customRender = this.columnHeadRender
          } else {
            installColumnRender(h)
          }
        })

        this.hhead = head
      })
    },

    /**
     * 这样做的性能是有问题的，需要重构优化
     */
    saveModelData: function () {
      if (this.hdata.length === 0) {
        return
      }

      const strData = JSON.stringify(this.model)

      const deepCopy = JSON.parse(strData)

      deepCopy.model.forEach(v => {
        delete v['meta']
      })

      saveDmtModel(deepCopy).then(response => {
        if (!this.model.mode) {
          this.model.code = response.code

          const h = this.$createElement
          this.$info({
            title: '提示消息',
            content: h('div', {}, [
              h('p', '模型保存成功.')
            ]),
            onOk () {}
          })
        }
      })
    },

    downloadTemplate: function () {
      const param = this.param

      param.values = this.dmtValues

      console.log('组装模板参数:', param)

      downloadTemplate(param).then(response => {
        const name = param.name + '.xlsx'
        const blob = new Blob([response])
        const url = window.URL.createObjectURL(blob)
        const alink = document.createElement('a')
        alink.style.display = 'none'
        alink.href = url
        alink.setAttribute('download', name)
        document.body.appendChild(alink)
        alink.click()
        document.body.removeChild(alink)

        // 这样会不会有前端的性能问题？
        // window.URL.removeObjectURL(url)
      })
    }

    // getDynamicModel: function () {
    //   const param = this.buildModel()

    //   if (!param) {
    //     return
    //   }

    //   this.hdata = []
    //   this.hhead = []

    //   getDmtModel(param).then(response => {
    //     const data = response.model
    //     const meta = response.meta
    //     const head = response.head

    //     this.model = response

    //     this.hdata = data
    //     this.hdata.forEach(record => {
    //       record.meta = meta
    //     })

    //     head.forEach(h => {
    //       if (h.cardinal) {
    //         h.customRender = this.columnHeadRender
    //       } else {
    //         installColumnRender(h)
    //       }
    //     })

    //     this.hhead = head
    //   })
    // }
  },
  mounted () {
  }
}

</script>

<style>
  /** 这里的这时的颜色样式为什么会不生效，字体可以生效。 */
  .mclass{
    color: blue;
    background-color: blueviolet;
  }

  .ant-table-thead > tr > th, .ant-table-tbody > tr > td {
    padding: 5px 5px;
  }

  .ant-table-row-hover > td{
    background-color: red;
    color: green;
  }

  table:hover, tr:hover, thead:hover {
    /* background: #20293c !important;*/
  }

  .ant-table-tbody > tr.ant-table-row:hover > td {
    background: none !important;
  }
</style>
